package com.njym.java.security.common.notify.config;

import com.github.qcloudsms.SmsSingleSender;
import com.njym.java.security.common.notify.AliyunSmsSender;
import com.njym.java.security.common.notify.NotifyService;
import com.njym.java.security.common.notify.TencentSmsSender;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(NotifyProperties.class)
public class NotifyAutoConfiguration {

    private final NotifyProperties properties;

    public NotifyAutoConfiguration(NotifyProperties properties) {
        this.properties = properties;
    }

    @Bean
    public NotifyService notifyService() {
        NotifyService notifyService = new NotifyService();

        NotifyProperties.Sms smsConfig = properties.getSms();
        if (smsConfig.isEnable()) {
            String active = smsConfig.getActive();
            if (active.equals("tencentSms")) {
                notifyService.setSmsSender(tencentSmsSender());
                notifyService.setSmsTemplate(smsConfig.getTencentSms().getTemplate());
            } else if (active.equals("aliyunSms")) {
                notifyService.setSmsSender(aliyunSmsSender());
                notifyService.setSmsTemplate(smsConfig.getAliyunSms().getTemplate());
            } else {
                throw new RuntimeException("当前短信模式 " + active + " 不支持");
            }
        }

        return notifyService;
    }


    @Bean
    public TencentSmsSender tencentSmsSender() {
        NotifyProperties.Sms smsConfig = properties.getSms();
        TencentSmsSender smsSender = new TencentSmsSender();
        smsSender.setSender(new SmsSingleSender(smsConfig.getTencentSms().getAppid(), smsConfig.getTencentSms().getAppkey()));
        return smsSender;
    }

    @Bean
    public AliyunSmsSender aliyunSmsSender() {
        NotifyProperties.Sms smsConfig = properties.getSms();
        smsConfig.getAliyunSms().getAccessKeyId();
        AliyunSmsSender smsSender = new AliyunSmsSender();
        smsSender.setAccessKeyId(smsConfig.getAliyunSms().getAccessKeyId());
        smsSender.setAccessKeySecret(smsConfig.getAliyunSms().getAccessKeySecret());
        smsSender.setSignName(smsConfig.getAliyunSms().getSignName());
        return smsSender;
    }
}
